﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HZY.Admin.Core
{
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using System.Net;
    using System.Security.Claims;
    using Toolkit;

    /// <summary>
    /// 异常过滤
    /// </summary>
    public class HZYAppExceptionFilter : IExceptionFilter, IOrderedFilter
    {

        public int Order { get; set; } = int.MaxValue - 10;

        public void OnException(ExceptionContext context)
        {
            var _Exception = context.Exception;
            if (_Exception is MessageBox _Error)
            {
                context.ExceptionHandled = true;
                context.HttpContext.Response.StatusCode = _Error.Model.StatusCode;

                var res = _Error.Model.Value;
                if (res is string) res = new { msg = res };

                var objectResult = new ObjectResult(res);
                objectResult.StatusCode = _Error.Model.StatusCode;
                context.Result = objectResult;
            }
            else
            {
                Tools.Log.Write(_Exception, context.HttpContext.Connection.RemoteIpAddress.ToString());//nlog 写入日志到 txt
                //context.Result = new StatusCodeResult((int)HttpStatusCode.InternalServerError);
                var objectResult = new ObjectResult($"服务端出现异常![异常消息：{_Exception.Message}]");
                objectResult.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Result = objectResult;
            }
        }

    }
}
